use crate::core::CTX;
use crate::domain::dto::PageRes;
use crate::domain::dto::project_dto::{ProjectCreateRequest, ProjectPageRequest, ProjectPageResponse, ProjectUpdateRequest};
use crate::domain::entity::project_entity::ProjectEntity;
use crate::mapper::project_mapper;
use crate::utils;

///  project_create 项目创建
pub async fn project_create(param: ProjectCreateRequest) -> rbatis::Result<bool> {
    tracing::info!("项目创建: {:?}", param);
    let project: ProjectEntity = param.into();
    let count = project_mapper::count_by_name(&mut CTX.db.clone(), &project.project_name.as_str()).await?;
    if count > 0 {
        return Err(rbatis::Error::from("存在相同的名称"))
    }
    let result = ProjectEntity::insert(&mut CTX.db.clone(), &project).await?;
    Ok(result.rows_affected == 1)
}

///  project_update 项目更新
pub async fn project_update(param: ProjectUpdateRequest) -> rbatis::Result<bool> {
    tracing::info!("项目更新: {:?}", param);
    let project_option = project_mapper::select_by_id(&mut CTX.db.clone(), param.id).await?;
    match project_option {
        Some(mut project) => {
            let project = project.update(param);
            let result = ProjectEntity::update_by_column(&mut CTX.db.clone(), &project, "id").await;
            match result {
                Ok(r) => Ok(r.rows_affected == 1),
                Err(err) => Err(err)
            }
        },
        None => Err(rbatis::Error::from("更新的项目不存在"))
    }
}

///  project_delete 项目删除
pub async fn project_delete(id: u64) -> rbatis::Result<bool> {
    tracing::info!("项目删除: {:?}", id);


    todo!()
}

///  project_pages 项目分页
pub async fn project_pages(param: ProjectPageRequest) -> rbatis::Result<PageRes<ProjectPageResponse>> {
    let (num,size) = utils::tool::page_tools(param.page.clone().unwrap(), param.limit.clone().unwrap());
    let list = project_mapper::select_project_page(&mut CTX.db.clone(), num, size, param.name.clone(), param.biz_id.clone()).await?;
    let total = project_mapper::select_project_count(&mut CTX.db.clone(), param.name.clone(), param.biz_id.clone()).await?;
    Ok(PageRes {
        page: param.page.clone().unwrap(),
        limit: param.limit.clone().unwrap(),
        total,
        row: list,
    })
}